// 导入 node.js 核心模块
const fs = require( 'fs' );
const path = require( 'path' );
// 导入 express 模块
const express = require( 'express' );
// 导入 multer 模块
const multer = require( 'multer' );

const dest = 'D:/uploads' ;

// 表示将上传的文件内容先存储在内存中
const storage = multer.memoryStorage();
const mu = multer( { storage: storage } );

const port = 8080 ;
const app = express();

app.use( express.static( 'public' ) );
app.use( express.urlencoded( {extended: false } ));
app.use( express.text() );
app.use( express.json() );

function process( original ){
    let suffix = path.extname( original );
    let prefix = original.substring( 0 , original.lastIndexOf( suffix ));
    let filename = prefix + '-' + Date.now() + suffix ;
    return filename ;
}

let first = mu.single( 'upfile' );
let s = first.toString() ;
console.log( s.substring(0,s.indexOf( ' {' )) );
let second = (req,resp)=>{
    console.log( req.file );
    const original = req.file.originalname ;
    let filename = process( original );
    console.log( filename );
    let pathname = path.resolve( dest , filename );
    fs.writeFile( pathname , req.file.buffer , err => {
        if( err ) {
            console.log( err );
            resp.send( '<h3>上传失败</h3>' );
        } else {
            resp.send( '<h3>上传成功</h3>' );
        }
    } );
}
app.post( '/upload/single' , first );
app.post( '/upload/single' , second );

app.post( '/upload/multiple' , mu.array('upfile',10) , (req,resp)=>{
    let files = req.files ;
    files.forEach( f => {
        console.log( f );
        let pathname = path.resolve( dest , process( f.originalname ) );
        fs.writeFileSync( pathname , f.buffer );
    });
    resp.send( '<h3>上传成功</h3>' );
});

app.listen( port );